<template>
  <el-dialog title="SPU配置" :visible.sync="dialogVisible" @close="closeDialog" width="1000px" destroy-on-close>
    <el-form :model="spuForm" label-position="right" label-width="100px" ref="spuForm" v-if="pageType === 'form'"
      :rules="rules">
      <el-form-item label="商品名称" prop="spuName">
        <el-input v-model="spuForm.spuName" placeholder="商品名称" :maxlength="15" />
      </el-form-item>
      <el-form-item label="卖点" prop="sellingPoints">
        <el-input v-model="spuForm.sellingPoints" placeholder="请输入卖点" :maxlength="15" />
      </el-form-item>
      <el-form-item label="原价" prop="originalPrice">
        <el-input-number v-model="spuForm.originalPrice" :min="0.01" :step="1" :precision="2"
          controls-position="right" />
      </el-form-item>
      <el-form-item label="拼单价" prop="groupBuyPrice">
        <el-input-number v-model="spuForm.groupBuyPrice" :min="0.01" :max="spuForm.originalPrice - 1" :step="1"
          :precision="2" controls-position="right" />
      </el-form-item>
      <el-form-item label="库存" prop="inventoryNumber">
        <el-input-number v-model="spuForm.inventoryNumber" :min="1" :step="1" controls-position="right" />
      </el-form-item>
      <el-form-item label="购买上限" prop="limitBuyNumber">
        <el-input-number v-model="spuForm.limitBuyNumber" :min="1" :step="1" controls-position="right" />
      </el-form-item>
      <el-form-item label="购买人群" prop="userType">
        <el-select v-model="spuForm.userType" placeholder="购买人群" @change="(value) => { changeSkuItem(value, index) }">
          <el-option label="所有用户" :value="0" />
          <el-option label="新用户" :value="1" />
          <el-option label="老用户" :value="2" />
        </el-select>
      </el-form-item>
      <el-form-item label="缩略图" prop="spuImage">
        <el-upload class="file-uploader" :action="`${baseUrl}/file/upload`" :show-file-list="false"
          :on-success="handleFileSuccess">
          <img v-if="spuForm.spuImage" :src="spuForm.spuImage" class="file">
          <i v-else class="el-icon-plus file-uploader-icon"></i>
        </el-upload>
      </el-form-item>
      <el-form-item label="详情页头图" prop="spuHeadImages">
        <el-upload class="file-uploader" :action="`${baseUrl}/file/upload`" list-type="picture-card"
          :on-success="(res) => { handleFormListSuccess(res, 'spuHeadImages') }"
          :before-remove="(file) => { removeImg(file, 'spuHeadImages') }" :file-list="spuForm.spuHeadImages">
          <!-- <img v-if="spuForm.experimentDetail.effectiveness" :src="addForm.productImage" class="file"> -->
          <i class="el-icon-plus file-uploader-icon"></i>
        </el-upload>
      </el-form-item>
      <el-form-item label="详情页长图" prop="spuDetailImages">
        <el-upload class="file-uploader" :action="`${baseUrl}/file/upload`" list-type="picture-card"
          :on-success="(res) => { handleFormListSuccess(res, 'spuDetailImages') }"
          :before-remove="(file) => { removeImg(file, 'spuDetailImages') }" :file-list="spuForm.spuDetailImages">
          <!-- <img v-if="addForm.experimentDetail.effectiveness" :src="addForm.productImage" class="file"> -->
          <i class="el-icon-plus file-uploader-icon"></i>
        </el-upload>
      </el-form-item>
      <el-form-item label="拼单规则" />
      <el-form-item label="成团人数" prop="groupBuyLimit">
        <el-input-number v-model="spuForm.groupBuyLimit" :min="1" controls-position="right" />
      </el-form-item>
      <el-form-item label="拼单时间" prop="groupBuyTime">
        <el-input-number v-model="spuForm.groupBuyTime" :min="1" controls-position="right" /> 小时
      </el-form-item>
      <el-form-item label="关联SKU" />
      <el-row v-for="(item, index) in spuForm.spuProductVoList">
        <el-col :span="8">
          <el-form-item label="名称" :prop="`spuProductVoList.${index}.productId`" :rules="rules.listSKUItem">
            <el-select v-model="item.productId" placeholder="SKU" @change="(value) => { changeSkuItem(value, index) }">
              <el-option v-for="item in skuList" :key="item.id" :label="item.productName" :value="item.id"
                :disabled="selectedSku.includes(item.id)" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="数量" :prop="`spuProductVoList.${index}.productNum`" :rules="rules.listSKUNumber">
            <el-input-number v-model="item.productNum" :min="1" controls-position="right" />
          </el-form-item>
        </el-col>
        <el-col :span="8" style="padding-left: 16px;" v-if="index > 0">
          <el-button icon="el-icon-minus" @click="removeCoreFunction(item, index)">删除</el-button>
        </el-col>
      </el-row>
      <el-form-item>
        <el-button icon="el-icon-plus" @click="addFormFunction"
          :disabled="spuForm.spuProductVoList[spuForm.spuProductVoList.length - 1].productId === undefined">新增一组信息</el-button>
      </el-form-item>
    </el-form>
    <el-descriptions title="SPU详情" :column="1" border v-if="pageType === 'view'">
      <el-descriptions-item label="商品名称">{{ detail.spuName }}</el-descriptions-item>
      <el-descriptions-item label="卖点">{{ detail.sellingPoints }}</el-descriptions-item>
      <el-descriptions-item label="原价">{{ detail.originalPrice }}</el-descriptions-item>
      <el-descriptions-item label="拼单价">{{ detail.groupBuyPrice }}</el-descriptions-item>
      <el-descriptions-item label="缩略图">
        <el-image style="width: 80px; height: 80px" :src="detail.spuImage" />
      </el-descriptions-item>
      <el-descriptions-item label="详情页头图">
        <el-image style="width: 100px; height: 100px" v-for="item in detail.spuHeadImages" :src="item"
          :preview-src-list="[item]" />
      </el-descriptions-item>
      <el-descriptions-item label="详情页长图">
        <el-image style="width: 100px; height: 100px" v-for="item in detail.spuDetailImages" :src="item"
          :preview-src-list="[item]" />
      </el-descriptions-item>
      <el-descriptions-item label="成团人数">{{ detail.groupBuyLimit }}</el-descriptions-item>
      <el-descriptions-item label="拼单时间">{{ detail.groupBuyPrice }}</el-descriptions-item>
      <el-descriptions-item label="拼单价">{{ detail.groupBuyPrice }}</el-descriptions-item>
    </el-descriptions>
    <el-descriptions :column="3" border v-for="(item, index) in spuProductVoListDetail" :title="`关联SKU${index + 1}详情`"
      style="margin-top: 10px;">
      <el-descriptions-item label="适用宠物类型">{{ petType[item.applicablePetTypes - 1] }}</el-descriptions-item>
      <el-descriptions-item label="适用年龄">{{ ageType[item.applicableAge] }}</el-descriptions-item>
      <el-descriptions-item label="保质期">{{ item.shelfLife }}月</el-descriptions-item>
      <el-descriptions-item label="功效">{{ item.efficacy }}</el-descriptions-item>
      <el-descriptions-item label="成分">{{ item.ingredients }}</el-descriptions-item>
    </el-descriptions>
    <span slot="footer" class="dialog-footer">
      <el-button @click="closeDialog">取 消</el-button>
      <el-button type="primary" v-if="pageType === 'form'" @click="handleSubmit">确 定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { querySelectSku, querySkuDetail, saveSpuItem } from '@/api/goods';
import { getBaseUrl } from "@/utils";

export default {
  props: ['getTableData'],
  data() {
    return {
      baseUrl: getBaseUrl(),
      petType: ['狗狗', '猫咪'],
      ageType: ['全年龄', '幼年', '成年', '老年'],
      pageType: 'form',
      dialogVisible: false,
      editId: undefined,
      initSpuForm: {
        spuName: undefined,
        sellingPoints: undefined,
        originalPrice: 1,
        groupBuyPrice: 1,
        groupBuyLimit: 1,
        inventoryNumber: undefined,
        limitBuyNumber: 1,
        userType: 0,
        spuImage: undefined,
        spuHeadImages: [],
        spuDetailImages: [],
        spuProductVoList: [{
          productId: undefined,
          productNum: undefined
        }],
      },
      spuForm: {
        spuName: undefined,
        sellingPoints: undefined,
        originalPrice: 1,
        groupBuyPrice: 1,
        groupBuyLimit: 1,
        inventoryNumber: undefined,
        limitBuyNumber: 1,
        userType: 0,
        spuImage: undefined,
        spuHeadImages: [],
        spuDetailImages: [],
        groupBuyTime: undefined,
        spuProductVoList: [{
          productId: undefined,
          productNum: undefined
        }],
      },
      rules: {
        spuName: [{ required: true, message: '请输入商品名称', trigger: 'blur' }],
        sellingPoints: [{ required: true, message: '请输入商品卖点', trigger: 'blur' }],
        originalPrice: [{ required: true, message: '请输入商品原价', trigger: 'blur' }],
        groupBuyLimit: [{ required: true, message: '请输入成团人数', trigger: 'blur' }],
        groupBuyTime: [{ required: true, message: '请输入拼单时间', trigger: 'blur' }],
        spuImage: [{ required: true, message: '请上传商品图片', trigger: 'blur' }],
        spuHeadImages: [{ required: true, message: '请上传商品头图', trigger: 'blur' }],
        spuDetailImages: [{ required: true, message: '请上传商品详情图', trigger: 'blur' }],
        listSKUItem: [{ required: true, message: '请选择SKU', trigger: 'blur' }],
        listSKUNumber: [{ required: true, message: '请设置数量', trigger: 'blur' }],
      },
      spuProductVoListDetail: [],
      selectedSku: [],
      skuList: [],
      detail: {}
    }
  },
  created() {

  },
  mounted() {
    this.getSkuList()
  },
  methods: {
    showModal(type) {
      this.pageType = type
      this.dialogVisible = true;
    },
    closeDialog() {
      if (this.pageType === 'form') {
        this.$refs.spuForm.resetFields();
        this.spuForm = this.initSpuForm
      }
      this.selectedSku = [];
      this.editId = undefined;
      this.dialogVisible = false;
    },
    changeFormValue(value) {
      this.spuForm = value;
      this.editId = value.id;
      if (value.disableSkuId) {
        value.disableSkuId.map(item => {
          this.changeSkuItem(item)
        })
      }
      this.showModal('form');
    },
    createSelectData(source, current) {
      // 这个方法是将枚举数据转换成list数据
      const typeList = [];
      Object.keys(source).map(item => {
        const typeItem = {
          value: item,
          label: source[item]
        };
        typeList.push(typeItem)
      })
      this[current] = typeList;
    },
    handleFileSuccess(res, file) {
      if (res.code === 200) {
        this.spuForm.spuImage = res.data.url
      }
    },
    handleFormListSuccess(res, obj) {
      if (res.code === 200) {
        const newList = this.spuForm[obj];
        const urlObj = new URL(res.data.url);
        const fileName = urlObj.pathname.split('/').pop();
        newList.push({
          uid: Date.now().toString(36) + Math.random().toString(36).substring(2),
          name: fileName,
          url: res.data.url
        });
        this.spuForm[obj] = newList
      }
    },
    removeImg(file, obj) {
      const fileIndex = this.spuForm[obj].indexOf(file);
      if (fileIndex !== -1) {
        this.spuForm[obj].splice(fileIndex, 1)
      }
    },
    addFormFunction() {
      this.spuForm.spuProductVoList.push({
        productId: undefined,
        productNum: undefined
      })
    },
    removeCoreFunction(item) {
      const index = this.spuForm.spuProductVoList.indexOf(item)
      if (index !== -1) {
        this.spuForm.spuProductVoList.splice(index, 1)
      }
      // 删除时，找到禁用的ID,删除禁用
      const newSelectedId = [...this.selectedSku];
      const selectedIndex = newSelectedId.findIndex(chunk => item.productId === chunk);
      newSelectedId.splice(selectedIndex, 1);
      this.selectedSku = newSelectedId;
      // 删除时找到关联SKU的详情 删除掉
      const newDetailList = [...this.spuProductVoListDetail];
      const currentIndex = newDetailList.findIndex(chunk => item.id === chunk.id);
      newDetailList.splice(currentIndex, 1);
      this.spuProductVoListDetail = newDetailList;
    },
    getSkuList() {
      querySelectSku().then(res => {
        if (res.code === 200) {
          this.skuList = res.rows
        }
      })
    },
    changeSkuItem(value, index) {
      //选中时，将选中的ID加入到disabled中
      if (!this.selectedSku.includes(value)) {
        this.selectedSku.splice(index, 1, value);
        querySkuDetail({
          id: value
        }).then(res => {
          if (res.code === 200) {
            this.spuProductVoListDetail.splice(index, 1, res.data);
          }
        })
      }
    },
    handleSubmit() {
      this.$refs.spuForm.validate((valid) => {
        if (valid) {
          const params = { ...this.spuForm };
          params.spuHeadImages = params.spuHeadImages.map(item => item.url)
          params.spuDetailImages = params.spuDetailImages.map(item => item.url)
          params.inventoryNumber = params.inventoryNumber || -1;
          saveSpuItem({
            ...params
          }).then(res => {
            if (res.code === 200) {
              this.closeDialog();
              this.getTableData();
            }
          })
        }
      })
    },

  }
}
</script>

<style scoped lang="scss">
.toolTipNumber {
  height: auto;

  .toolTipNumberFooter {
    margin-top: 16px;
    display: flex;
    align-items: center;
    justify-content: center;
  }
}

.file-uploader {
  &::v-deep .el-upload {
    width: 150px;
    height: 150px;
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;

    &:hover {
      border-color: #409EFF;
    }

  }

  .file-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 148px;
    height: 148px;
    line-height: 148px;
    text-align: center;
  }

  .file {
    width: 148px;
    height: 148px;
    display: block;
  }
}
</style>
